/**
 * This code is released under lgpl v3 license.
 * All rights reserved.
*/

package bridge;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.user.client.Window;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * wrapper for FABridge overlay type, for event system mapping
 * @author yuan yunchang    dukerr@gmail.com
 */
public class FABridgeWrapper {
    private  static FABridgeWrapper _instance = null;
    //private Map<String ,JavaScriptObject> eventProxys = new HashMap<String,JavaScriptObject>();
      JavaScriptObject proxy =null;
    private Map<String,List<InitCallback>> initCallbacksMap  = new HashMap<String,List<InitCallback>>();
    public static FABridgeWrapper get(){
        if(_instance==null){
            _instance = new FABridgeWrapper();
        }
        return _instance;
    }
    public void addInitCallback(String bridgeName ,InitCallback callback){
        if(proxy==null){
            initProxy(this);
        }
        List<InitCallback> callbacks = initCallbacksMap.get(bridgeName);
        if(callbacks==null){
            callbacks = new ArrayList<InitCallback>();
            initCallbacksMap.put(bridgeName, callbacks);
        }
        callbacks.add(callback);
        FABridge.get().addInitializationCallback(bridgeName, proxy);
    }
//    public static FABridge getBridge(){
//        return FABridge.get();
//    }
    private native void initProxy(FABridgeWrapper wrapper)/*-{
    wrapper.@bridge.FABridgeWrapper::proxy = function(){
        var inst = this
        wrapper.@bridge.FABridgeWrapper::dispatchEvent(Lbridge/FABridgeInstance;)(inst)
     }
    }-*/;
    private void dispatchEvent(FABridgeInstance bridgeInstance){
        String name = bridgeInstance.getName();
        
        //Window.alert("in dispatchEvent,instance : "+bridgeInstance);
        //Window.alert("in dispatchEvent,name: "+name);
        List<InitCallback> callbacks = initCallbacksMap.get(name);
        if(callbacks==null){
            throw new IllegalStateException("can not found InitCallback for bridge: "+name);
        }
        for(InitCallback callback :callbacks){
            callback.initComplete(bridgeInstance);
        }
    }
    
    private FABridgeWrapper() {
    }

}
